package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @ClassNameOrderTask
 * @Description TODO
 * @Author钰玟
 * @Date2025/2/17 下午1:51
 * @Version 1.0
 **/

/**
 * 订单超时任务
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper  orderMapper;

    @Scheduled(cron = "0 * * * * ? ")// 每分钟执行一次
    public void orderTimeOutTask() {
        log.info("订单超时任务执行{}", LocalDateTime.now());

        LocalDateTime timeOut = LocalDateTime.now().plusMinutes(-15);//超时时间
        List<Orders> orders = orderMapper.getOrderByStatusAndOrderTimeLF(Orders.PENDING_PAYMENT,timeOut);
        if(orders !=null &&  orders.size()>0){
            for (Orders order : orders) {
                order.setCancelTime(LocalDateTime.now());
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时自动取消");
                orderMapper.update(order);
            }
        }
    }


    @Scheduled(cron = "0 0 1 * * ? ") //  每天凌晨1点执行
    public void AutoCheckOrderIsCompleted() {
        log.info("自动完成派送任务执行{}", LocalDateTime.now());

        // 查询所有已完成订单
        List<Orders> completedOrders = orderMapper.getOrderByStatusAndOrderTimeLF(Orders.DELIVERY_IN_PROGRESS,LocalDateTime.now().plusHours(-1));
        if(completedOrders !=null && completedOrders.size()>0){
            for (Orders order : completedOrders) {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            }
        }
    }



}
